package ext.tianma.part.util.updateIBAValues;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import ext.com.iba.IBAUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.part.resolution.Resolution;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.iba.definition.StringDefinition;
import wt.iba.value.StringValue;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.query.KeywordExpression;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.ClientTypedUtility;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.type.Typed;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.Iterated;
import wt.vc.config.ConfigHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.config.LatestConfigSpec;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.wip.WorkInProgressHelper;

public class IbaAttributeUtil {

	public static final String discardState = "OBSOLESCENCE";// 废弃状态
	public static final String FinishedGoodType = "cn.tianma.FinishedGood";// 成品
	public static final String SemiFinishedGoodType = "cn.tianma.SemiFinishedGood";// 半成品

	/****
	 * 批量刷新系统中非废弃状态的所有半成品
	 * 
	 * @return
	 * @throws WTException
	 */
	public static List<WTPart> updateIBAValue() {
		System.out.println("======>>>>start===>>updateIBAValue");
		getRawMaterial();
		WTArrayList partList = new WTArrayList();

		return partList;
	}

	public static List<WTPart> getRawMaterial() {
		System.out.println("======>>>>star3333t===>>updateIBAValue");
		List<WTPart> list = new ArrayList<WTPart>();
		
		try {
			QuerySpec qs = new QuerySpec();
			int docIndex = qs.appendClassList(WTPart.class, true);
			View view = ViewHelper.service.getView("Design");

			// 增加过滤条件：iba属性存在值
			TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(FinishedGoodType);
			SearchCondition scOther = new SearchCondition(WTPart.class,
					Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
							+ TypeDefinitionForeignKey.BRANCH_ID,
					SearchCondition.EQUAL, clientType.getKey().getBranchId());
			qs.appendWhere(scOther, new int[] { 0 });
			qs.appendAnd();
			SearchCondition scState = new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE,
					SearchCondition.NOT_EQUAL, discardState);
			qs.appendWhere(scState, new int[] { 0 });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			QueryResult qr = PersistenceHelper.manager.find(qs);
			System.out.println("======>>>>start44===>>updateIBAValue" + qs);
			System.out.println("======>>>>start55===>>updateIBAValue" + qr.size());
			int count = 1;
			while (qr.hasMoreElements()) {
				WTArrayList partList = new WTArrayList();
				System.out.println("count==>>" + count);
				Object obj[] = (Object[]) qr.nextElement();
				if (obj[0] instanceof WTPart) {
					WTPart part = (WTPart) obj[0];
					WTPart partleast = getLatestPartByPartMaster((WTPartMaster) part.getMaster());
					part = (WTPart) GenericUtil.checkout(part);
					
					System.out.println("jianchujianru  ====   ");
					
					GenericUtil.checkin(part);
					System.out.println("IBA===>>>"+(String) IBAUtil.getIBAValue(part, "finishedGoodResolutionCode"));// 分辨率(横)
					partList.add(partleast);
				}
				System.out.println("partList===>>" + partList.size());
				System.out.println("partList===>>" + partList);
				count++;
				// 调用发送ERP接口
				ext.generic.erp.service.PartReleaseService.releasePersistable(partList,
						ext.generic.erp.common.CommonUtil.getCurrentTime());
			}
			
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTPropertyVetoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	public static List<WTPart> sengToERP() {
		System.out.println("======>>>>sengToERP===>>updateIBAValue");
		List<WTPart> list = new ArrayList<WTPart>();
		
		try {
			QuerySpec qs = new QuerySpec();
			int docIndex = qs.appendClassList(WTPart.class, true);
			View view = ViewHelper.service.getView("Design");

			// 增加过滤条件：iba属性存在值
			TypeDefinitionReference clientType = ClientTypedUtility.getTypeDefinitionReference(SemiFinishedGoodType);
			SearchCondition scOther = new SearchCondition(WTPart.class,
					Typed.TYPE_DEFINITION_REFERENCE + "." + TypeDefinitionReference.KEY + "."
							+ TypeDefinitionForeignKey.BRANCH_ID,
					SearchCondition.EQUAL, clientType.getKey().getBranchId());
			qs.appendWhere(scOther, new int[] { 0 });
			qs.appendAnd();
			SearchCondition scState = new SearchCondition(WTPart.class, WTPart.LIFE_CYCLE_STATE,
					SearchCondition.NOT_EQUAL, discardState);
			qs.appendWhere(scState, new int[] { 0 });
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(WTPart.class, "view.key.id", SearchCondition.NOT_EQUAL,
					view.getPersistInfo().getObjectIdentifier().getId()));
			qs.appendAnd();
			qs.appendWhere(new SearchCondition(new KeywordExpression("A0.latestiterationinfo"), SearchCondition.EQUAL,
					new KeywordExpression("1")));
			QueryResult qr = PersistenceHelper.manager.find(qs);
			System.out.println("======>>>>start44===>>updateIBAValue" + qs);
			System.out.println("qr===>>>"+qr);
			System.out.println("======>>>>start55===>>updateIBAValue" + qr.size());
			WTArrayList partList = new WTArrayList();
			while (qr.hasMoreElements()) {
				
				Object obj[] = (Object[]) qr.nextElement();
				if (obj[0] instanceof WTPart) {
					WTPart part = (WTPart) obj[0];
					if (!isCheckOut(part)) {
						System.out.println("===>>>"+part.getNumber());
						partList.add(part);
					}
				}
				System.out.println("partList==>>" + partList.size());
				// 调用发送ERP接口
				ext.generic.erp.service.PartReleaseService.releasePersistable(partList,
						ext.generic.erp.common.CommonUtil.getCurrentTime());

			}
			
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (QueryException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 * 
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
			String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}

	/**
	 * 判断该零件是否已经出库
	 * 
	 * @param part
	 *            零件对象
	 * @return true:出库<br>
	 *         false:未出库
	 */
	public static boolean isCheckOut(WTPart part) {
		boolean isCheckOut = false;
		if (part != null) {
			try {
				isCheckOut = WorkInProgressHelper.isCheckedOut(part);/* 获取零件的出库状态 */
			} catch (WTException e) {
				e.printStackTrace();
			}
		} // end if

		return isCheckOut;
	}

	public static WTPart getLatestPartByPartMaster(WTPartMaster paramWTPartMaster) throws WTException {
		Iterated localIterated = null;
		boolean bool = false;
		LatestConfigSpec localLatestConfigSpec = new LatestConfigSpec();

		QueryResult localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster,
				localLatestConfigSpec);
		if ((localQueryResult != null) && (localQueryResult.size() <= 0)) {
			ConfigSpec localConfigSpec = ConfigHelper.service.getDefaultConfigSpecFor(WTPartMaster.class);
			localQueryResult = ConfigHelper.service.filteredIterationsOf(paramWTPartMaster, localConfigSpec);
		}

		while ((localQueryResult.hasMoreElements()) && (!bool)) {
			localIterated = (Iterated) localQueryResult.nextElement();
			bool = localIterated.isLatestIteration();
		}
		return (WTPart) localIterated;
	}
}
